package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import com.sky.vo.SetmealVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description 菜品服务实现类
 * @Author shh
 * @Date 2025-10-06
 */
@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;

    /**
     * 新增菜品
     *
     * @param dishDTO
     */
    //涉及到多张表的操作，需要使用事务进行管理
    @Transactional
    public void addDish(DishDTO dishDTO) {

        //1.构建菜品基本信息数据，将其存入dish表中
        Dish dish = new Dish();
        //拷贝属性值
        BeanUtils.copyProperties(dishDTO, dish);
        //调用mapper保存
        dishMapper.insert(dish);
        log.info("新增菜品，id为：{}", dish.getId());
        //2.构建菜品口味信息数据，将其存入dish_flavor表中
        List<DishFlavor> list = dishDTO.getFlavors();
        //关联菜品id
        list.forEach(item -> item.setDishId(dish.getId()));
        //调用mapper保存
        dishFlavorMapper.insertBatch(list);
        log.info("新增菜品口味，数量为：{}", list.size());
    }

    /**
     * 分页查询菜品
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageDish(DishPageQueryDTO dishPageQueryDTO) {
        //1.封装分页查询参数
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        //2.调用mapper查询分页数据
        Page<DishVO> page = dishMapper.page(dishPageQueryDTO);
        log.info("分页查询菜品，共{}条", page.getTotal());
        //3.封装分页结果

        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 批量删除菜品
     *
     * @param ids
     */
    @Override
    @Transactional
    public void deleteDish(List<Long> ids) {
        //1.判断菜品是否启用，若启用则不能删除
        //判断是否启用
        ids.forEach(id -> {
            Dish dish = dishMapper.selectById(id);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });
        //2.判断是否与套餐关联，若关联则不能删除
        //判断是否与套餐关联
        //判断是否与套餐关联
        //判断当前菜品是否能够删除---是否被套餐关联了？？
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (setmealIds != null && setmealIds.size() > 0) {
            //当前菜品被套餐关联了，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }


        //3.删除dish表中对应的菜品数据
        dishMapper.deleteBatch(ids);
        log.info("删除dish表中{}条数据", ids.size());
        //4.删除dish_flavor表中与菜品关联的口味数据
        dishFlavorMapper.deleteBatch(ids);
        log.info("删除dish_flavor表中{}条数据", ids.size());


    }

    @Override
    //@Transactional//查询操作需要开启事务，否则会报错：org.apache.ibatis.exceptions.PersistenceException:查询不需要
    public DishVO getDishById(Long id) {
        //1.根据菜品id查询菜品基本信息
        Dish dish = dishMapper.selectById(id);
        //2.根据菜品id查询口味列表数据
        List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(id);
        //3.构造DishVo对象并返回
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(flavors);
        return dishVO;
    }

    /**
     * @Description 更新菜品
     * @Author shh
     * @Date 2025-10-06
     */
    @Override
    @Transactional//更新操作需要开启事务，否则会报错：org.apache.ibatis.exceptions.PersistenceException:更新操作需要开启事务
    public void updateDish(DishDTO dishDTO) {

        //1.修改菜品基本信息数据，将其存入dish表中
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);
        log.info("修改菜品，id为：{}", dish.getId());
        //2.修改菜品口味信息数据，将其存入dish_flavor表中
        //删除原有的口味数据
        dishFlavorMapper.deleteBatchByDishId(dishDTO.getId());
        log.info("删除dish_flavor表中{}条数据", 1);
        //插入新的口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();//获取菜品口味列表
        if(flavors != null && flavors.size() > 0) {
            flavors.forEach(item -> item.setDishId(dishDTO.getId()));//关联菜品id
            dishFlavorMapper.insertBatch(flavors);
        }
        log.info("新增菜品口味，数量为：{}", flavors.size());
    }
    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }
    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
    /**
     * 更新菜品状态
     * @param status
     * @param id
     */
    @Override
    public void updateStatus(Integer status, long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.updateStatus(dish);
    }

}
